package com.view;


import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.View;

import com.data.Common;

/**
 * Y轴
 * Created by White
 * Email：whitelaning@qq.com
 */

public class AxisYView extends View {

    private float xPoint = 0;// 原点X坐标
    private float yPoint = 0;// 原点Y坐标
    private float xLength = 0;// X轴长度
    private float yLength = 0;// Y轴长度

    private int[] yLabelArray = {};// Y轴标签,用于计算

    private Paint mPaint = new Paint();
    private Rect mRect = new Rect();

    private float[] mBegins = {};//Y轴刻度的y坐标

    private float yScaleEachLength;//均分后刻度之间的长度
    private int yScaleEachHeight = 15;//每个刻度值的高度

    private int yBoundaryValue = 5;//防止布局和边界重叠而显示不全
    private int yScaleLabelOffset = 30;//文字和轴线的偏移量

    private int yStrokeWidth = 2;//画笔宽度

    public AxisYView(Context context) {
        super(context);
    }

    public void initValue(float Height, float Width) {
        xLength = Width;
        yLength = Height;
        yLabelArray = Common.yScaleArrayLabelHeight;
        yScaleEachLength = Common.yScaleEachLength;

        initPaint();
        getPoint();
    }

    private void initPaint() {
        // 设置画笔
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.FILL);// 设置画笔样式
        mPaint.setAntiAlias(true);// 去锯齿
        mPaint.setColor(Common.yScaleColor);// 设置颜色
        mPaint.setTextSize(25);// 设置字体
        mPaint.setStrokeWidth(yStrokeWidth);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        drawYAxisLine(canvas);
        drawYAxisLabel(canvas);
    }

    private void drawYAxisLabel(Canvas canvas) {
        for (int i = 0; yLabelArray != null && i < yLabelArray.length; i++) {
            // 画Y轴刻度标签
            if (i < yLabelArray.length) {
                //绘制文字
                mPaint.getTextBounds(String.valueOf(yLabelArray[i]), 0, String.valueOf(yLabelArray[i]).length(), mRect);
                int width = mRect.width();//文本的宽度
                int height = mRect.height();//文本的高度

                canvas.drawText(String.valueOf(yLabelArray[i]),
                        xLength - yStrokeWidth / 2 - width - yScaleLabelOffset,
                        mBegins[i] - height / 2,
                        mPaint);
            }
        }
    }

    private void drawYAxisLine(Canvas canvas) {
        canvas.drawLine(xLength - yStrokeWidth / 2, yPoint, xLength - yStrokeWidth / 2, yLength, mPaint);
    }

    private void getPoint() {
        mBegins = new float[yLabelArray.length];

        for (int i = 0; i < yLabelArray.length; i++) {
            if (i == 0) {
                mBegins[i] = yLength;
            } else {
                mBegins[i] = mBegins[i - 1] - yScaleEachLength;
            }
        }
    }
}
